package SystemA;

/******************************************************************************************************************
* File:SecurityMonitor.java
* Course: 17655
* Project: Assignment A3
* Copyright: Copyright (c) 2013 Carnegie Mellon University
* Versions:
*	1.0 March 2013 - subbu
*
* 
******************************************************************************************************************/
import EventPackage.*;
import InstrumentationPackage.*;

class SecurityMonitor extends Thread
{
	private EventManagerInterface em = null;// Interface object to the event manager
	private String EvtMgrIP = null;			// Event Manager IP address
	boolean Registered = true;				// Signifies that this class is registered with an event manager.
	MessageWindow mw = null;				// This is the message window
	boolean ON = true;						//indicates if system is armed or disarmed
	Indicator si;
	String AlertType="";

	public SecurityMonitor()
	{
		// event manager is on the local system

		try
		{
			// Here we create an event manager interface object. This assumes
			// that the event manager is on the local machine

			em = new EventManagerInterface();

		}

		catch (Exception e)
		{
			System.out.println("SecurityMonitor::Error instantiating event manager interface: " + e);
			Registered = false;

		} // catch

	} //Constructor

	public SecurityMonitor( String EvmIpAddress )
	{
		// event manager is not on the local system

		EvtMgrIP = EvmIpAddress;

		try
		{
			// Here we create an event manager interface object. This assumes
			// that the event manager is NOT on the local machine

			em = new EventManagerInterface( EvtMgrIP );
		}

		catch (Exception e)
		{
			System.out.println("SecurityMonitor::Error instantiating event manager interface: " + e);
			Registered = false;

		} // catch

	} // Constructor

	public void run()
	{
		Event Evt = null;				// Event object
		EventQueue eq = null;			// Message Queue
		int EvtId = 0;					// User specified event ID
		int	Delay = 1000;				// The loop delay (1 second)
		boolean Done = false;			// Loop termination flag
			// 

		if (em != null)
		{
			// Now we create the SecurtyMonitor status and message panel
		

			mw = new MessageWindow("Security Monitoring Console", 100, 100);
			si = new Indicator ("ARMED", mw.GetX()+ mw.Width(), 0); //indicates status of security system
			
			mw.WriteMessage( "Registered with the event manager." );

	    	try
	    	{
				mw.WriteMessage("   Participant id: " + em.GetMyId() );
				mw.WriteMessage("   Registration Time: " + em.GetRegistrationTime() );

			} // try

	    	catch (Exception e)
			{
				System.out.println("Error:: " + e);

			} // catch

			/********************************************************************
			** Here we start the main simulation loop
			*********************************************************************/

			while ( !Done )
			{
				// Here we get our event queue from the event manager

        try
				{
					eq = em.GetEventQueue();

				} // try

				catch( Exception e )
				{
					mw.WriteMessage("Error getting event queue::" + e );

				} // catch

				// If there are messages in the queue, we read through them.
				// We are looking for EventIDs = 6.
				//Note that we get all the messages at once... there is a 1
				// second delay between samples,.. so the assumption is that there should
				// only be a message at most. If there are more, it is the last message
				// that will effect the state of the security sytem

				String AlertString = new String();
				int qlen = eq.GetSize();

				for ( int i = 0; i < qlen; i++ )
				{
					Evt = eq.GetEvent();

					if ( (Evt.GetEventId() == 6)) // Security alert reading
					{
						try
						{
							AlertType= Evt.GetMessage();
							//set indicator color based on alert type received
							switch(AlertType)
							{
							case "WB": 
									if (ON) si.SetLampColorAndMessage("WINDW BRK!",1);
									AlertString = "Window Break Detected!"; //this string will be displayed in the console
									break;
							case "DB": 	
									if (ON) si.SetLampColorAndMessage("DOOR BRK!",2);
									AlertString = "Door Break Detected!"; //this string will be displayed in the console
									break;
							case "MD": 
									if (ON) si.SetLampColorAndMessage("MOV DTCTD!",1);
									AlertString = "Movement Detected!"; //this string will be displayed in the console
									break;
							case "RST": 
									if (ON) si.SetLampColorAndMessage("ARMED!",0);
									AlertString = "All Alerts cleared.System Armed"; //this string will be displayed in the console
									break;
							
                                                        case "ON": 
									if (ON) si.SetLampColorAndMessage("ARMED!",0);
									AlertString = "Arming system for security events"; //this string will be displayed in the console
                                                                        break;
                                                        
                                                        case "OFF": 
									si.SetLampColorAndMessage("NOT ARMED!",2);
									mw.WriteMessage( "Disarming system...security events are not reported" );
									break;
               				default: break;
							}
                                                       
                                                        //only print messages if the system is armed
                                                        if (ON) mw.WriteMessage(AlertString);

						} // try

						catch( Exception e )
						{
							mw.WriteMessage("Error reading Security alert: " + e);

						} // catch
					
					} // if
					
				// If the event ID == 99 then this is a signal that the simulation
				// is to end. At this point, the loop termination flag is set to
				// true and this process unregisters from the event manager.

				if ( Evt.GetEventId() == 99 )
				{
					Done = true;

					try
					{
						em.UnRegister();

			    	} // try

			    	catch (Exception e)
			    	{
						mw.WriteMessage("Error unregistering: " + e);

			    	} // catch

                                    mw.WriteMessage( "\n\nSimulation Stopped. \n");

					// Get rid of the indicators. The message panel is left for the
					// user to exit so they can see the last message posted.

					si.dispose();

                                    } // if

                                } //for	                            	
					
				// This delay slows down the sample rate to Delay milliseconds
	
					try
					{
						Thread.sleep( Delay );
	
					} // try
	
					catch( Exception e )
					{
						System.out.println( "Sleep error:: " + e );
	
					} // catch

			} // while

		} else {

			System.out.println("Unable to register with the event manager.\n\n" );

		} // if

	} // main

	/***************************************************************************
	* CONCRETE METHOD:: IsRegistered
	* Purpose: This method returns the registered status
	*
	* Arguments: none
	*
	* Returns: boolean true if registered, false if not registered
	*
	* Exceptions: None
	*
	***************************************************************************/

	public boolean IsRegistered()
	{
		return( Registered );

	} 

	/***************************************************************************
	* CONCRETE METHOD:: Halt
	* Purpose: This method posts an event that stops the environmental control
	*		   system.
	*
	* Arguments: none
	*
	* Returns: none
	*
	* Exceptions: Posting to event manager exception
	*
	***************************************************************************/

	public void Halt()
	{
		mw.WriteMessage( "***HALT MESSAGE RECEIVED - SHUTTING DOWN SYSTEM***" );

		// Here we create the stop event.

		Event evt;

		evt = new Event( (int) 99, "XXX" );

		// Here we send the event to the event manager.

		try
		{
			em.SendEvent( evt );

		} // try

		catch (Exception e)
		{
			System.out.println("Error sending halt message:: " + e);

		} // catch

	} // Halt
	public void ArmSystem()
	{
		Event evt;
		evt = new Event( (int) 6, "ON" );
		try
		{
			em.SendEvent( evt );
                        ON = true;

		} // try

		catch (Exception e)
		{
			System.out.println("Error sending ON message:: " + e);

		} // catch
			
		
	}
	public void DisarmSystem() //method to disarm the security system
	{
		Event evt;
		evt = new Event( (int) 6, "OFF" );
		try
		{
			em.SendEvent( evt );
                        ON = false;

		} // try

		catch (Exception e)
		{
			System.out.println("Error sending OFF message:: " + e);

		} // catch
	}


} // SecurityMonitor